package com.yonyou.cyxdms.sysAuth.service.service.notification.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.cyx.framework.service.excel.ExcelExportColumn;
import com.yonyou.cyx.framework.service.excel.ExcelGenerator;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.notification.NotificationFeedbackDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.notification.NotificationFeedbackPO;
import com.yonyou.cyxdms.sysAuth.service.mapper.OrgRoleMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.notification.NotificationFeedbackMapper;
import com.yonyou.cyxdms.sysAuth.service.service.notification.NotificationFeedbackService;
import com.yonyou.cyxdms.sysAuth.service.vo.notification.NotificationSearchVO;
import com.yonyou.cyxdms.sysAuth.service.vo.notification.NotificationUserVO;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants.*;


/**
 * <p>
 * 通知通告反馈记录表 服务实现类
 * </p>
 *
 * @author chengliang
 * @since 2019-09-25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class NotificationFeedbackServiceImpl extends ServiceImpl<NotificationFeedbackMapper, NotificationFeedbackPO> implements NotificationFeedbackService {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(NotificationFeedbackServiceImpl.class);

    @Autowired
    NotificationFeedbackMapper notificationFeedbackMapper;

    @Autowired
    private ExcelGenerator excelService;

    @Autowired
    private OrgRoleMapper orgRoleMapper;

    /**
     * 分页查询对应数据
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     * @author chengliang
     * @since 2019-09-25
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        // 获取总条数
        page.setRecords(notificationFeedbackMapper.selectPageBySql(page, queryCondition));
        return page;
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param queryCondition 查询条件
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author chengliang
     * @since 2019-09-25
     */
    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> selectListBySql(Map<String, Object> queryCondition) {
        return notificationFeedbackMapper.selectListBySql(queryCondition);
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param id 主键ID
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author chengliang
     * @since 2019-09-25
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getById(Long id) {
        NotificationFeedbackPO notificationfeedbackpo = notificationFeedbackMapper.selectById(id);
        if (notificationfeedbackpo != null) {
            return notificationfeedbackpo.toMaps();
        } else {
            throw new DALException("查询失败,没有符合条件的数据");
        }
    }

    /**
     * 根据DTO 进行数据新增
     *
     * @param notificationFeedbackDTO 页面DTO
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author chengliang
     * @since 2019-09-25
     */
    @Override
    public Map<String, Object> insert(NotificationFeedbackDTO notificationFeedbackDTO) {
        //对对象进行赋值操作
        NotificationFeedbackPO notificationfeedbackpo = notificationFeedbackDTO.transDtoToPo(NotificationFeedbackPO.class);
        //执行插入
        notificationFeedbackMapper.insert(notificationfeedbackpo);
        //返回插入的值
        return notificationFeedbackMapper.selectById(notificationfeedbackpo.getNotificationFeedbackId()).toMaps();
    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param id                      主键ID
     * @param notificationFeedbackDTO 页面DTO
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author chengliang
     * @since 2019-09-25
     */
    @Override
    public Map<String, Object> update(Long id, NotificationFeedbackDTO notificationFeedbackDTO) {
        NotificationFeedbackPO notificationfeedbackpo = notificationFeedbackMapper.selectById(id);
        //对对象进行赋值操作
        notificationFeedbackDTO.transDtoToPo(notificationfeedbackpo);
        //执行更新
        notificationFeedbackMapper.updateById(notificationfeedbackpo);
        return notificationfeedbackpo.toMaps();
    }

    /**
     * 根据ID 进行删除数据
     *
     * @param id
     * @return void
     * @author chengliang
     * @since 2019-09-25
     */
    @Override
    public void deleteById(Long id) {
        int deleteCount = notificationFeedbackMapper.deleteById(id);
        logger.debug("删除数量：{}", deleteCount);
        if (deleteCount <= 0) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

    /**
     * 根据ids 进行删除
     *
     * @param ids
     * @return void
     * @author chengliang
     * @since 2019-09-25
     */
    @Override
    public void deleteBatchIds(String ids) {
        List<Long> longList = StringUtils.convertStrToArray(ids, ",", Long.class);
        int deleteCount = notificationFeedbackMapper.deleteBatchIds(longList);
        logger.debug("删除数量：{}", deleteCount);
        if (deleteCount != longList.size()) {
            throw new DALException("删除失败,没有符合条件的数据");
        }
    }

    @Override
    public void exportExcel(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        String type = (String) queryParam.get("type");
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryParam.put("appId", loginInfoDto.getAppId());
        switch (type) {
            case OEM_READ: // 厂端已读人员
                this.exportOemRead(queryParam, request, response);
                break;
            case DEALER_READ: // 经销商端已读人员
                this.exportDealerRead(queryParam, request, response);
                break;
            case OEM_NO_READ: // 厂端未读人员
                this.exportOemNoRead(queryParam, request, response);
                break;
            case DEALER_NO_READ:
                this.exportDealerNoRead(queryParam, request, response);
                break;
            default:
                break;
        }

    }

    @Override
    public IPage<Map<String, Object>> getNotificationList(Page<Map<String, Object>> page, Map<String, Object> queryCondition) {
        // 需要获取用户信息
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryCondition.put("feedbackUser", loginInfoDto.getUserId());
        queryCondition.put("appId", loginInfoDto.getAppId());
        // 获取总条数
        page.setRecords(notificationFeedbackMapper.getNotificationList(page, queryCondition));
        return page;
    }

    @Override
    public Integer selectbyuid(Integer notificationId, Integer userId) {
        return notificationFeedbackMapper.selectByUId(notificationId, userId);
    }

    /**
     * 厂端员工公告查看
     * 李贺
     * 2019/12/4
     */
    @Override
    public Page<NotificationUserVO> factoryUserNotification(Page<NotificationUserVO> page, NotificationSearchVO notificationSearchVO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        notificationSearchVO.setAppId(loginInfoDto.getAppId());
        notificationSearchVO.setUserId(loginInfoDto.getUserId());
        notificationSearchVO.setRoles(orgRoleMapper.getRoleIdsByUserOrgId(loginInfoDto.getUserOrgId()));
        return page.setRecords(notificationFeedbackMapper.factoryUserNotification(page, notificationSearchVO));
    }

    /**
     * 厂端员工公告查看后新增一条状态
     * 李贺
     * 2019/12/4
     */
    @Override
    public NotificationUserVO addFactoryBack(Long notificationId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Integer count = notificationFeedbackMapper.selectByUId(notificationId.intValue(), loginInfoDto.getUserId().intValue());
        if (count == 0) {
            NotificationFeedbackPO notificationfeedbackpo = new NotificationFeedbackPO();
            notificationfeedbackpo.setStatus(1);
            notificationfeedbackpo.setIsDealer(ManageDictCodeConstants.NO_IS_LOCK);
            notificationfeedbackpo.setFeedbackTime(LocalDateTime.now());
            notificationfeedbackpo.setFeedbackUserName(loginInfoDto.getUserName());
            notificationfeedbackpo.setFeedbackUser(loginInfoDto.getUserId());
            notificationfeedbackpo.setNotificationId(notificationId);
            notificationFeedbackMapper.insert(notificationfeedbackpo);
        }
        return notificationFeedbackMapper.factoryUserNotificationItem(notificationId);
    }

    // 厂端已读人员
    private void exportOemRead(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        List<Map> resultList = notificationFeedbackMapper.selectListBySql4Excel(queryParam);

        Map<String, List<Map>> excelData = new HashMap<>();
        excelData.put("厂端已读人员信息", resultList);
        List<ExcelExportColumn> exportColumnList = new ArrayList<>();
        exportColumnList.add(new ExcelExportColumn("feedbackUserName", "用户名"));
        exportColumnList.add(new ExcelExportColumn("feedbackTime", "首次阅读时间")); // TODO 存储首次阅读时间要判断
        excelService.generateExcel(excelData, exportColumnList, "厂端已读人员列表.xls", request, response);

    }

    // 经销商端已读人员
    private void exportDealerRead(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        List<Map> resultList = notificationFeedbackMapper.selectListBySql4Excel(queryParam);

        Map<String, List<Map>> excelData = new HashMap<>();
        excelData.put("经销商端已读人员信息", resultList);
        List<ExcelExportColumn> exportColumnList = new ArrayList<>();

        exportColumnList.add(new ExcelExportColumn("ownerCode", "经销商代码"));
        exportColumnList.add(new ExcelExportColumn("dealerName", "经销商名称"));
        exportColumnList.add(new ExcelExportColumn("feedbackUserName", "员工姓名"));
        exportColumnList.add(new ExcelExportColumn("feedbackTime", "首次阅读时间")); // TODO 存储首次阅读时间要判断

        excelService.generateExcel(excelData, exportColumnList, "经销商端已读人员列表.xls", request, response);
    }

    // 厂端未读人员
    private void exportOemNoRead(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        List<Map> resultList = notificationFeedbackMapper.selectListBySql4Excel(queryParam);

        Map<String, List<Map>> excelData = new HashMap<>();
        excelData.put("厂端未读人员信息", resultList);
        List<ExcelExportColumn> exportColumnList = new ArrayList<>();

        exportColumnList.add(new ExcelExportColumn("feedbackUserName", "用户名"));

        excelService.generateExcel(excelData, exportColumnList, "厂端未读人员列表.xls", request, response);
    }

    // 经销商端未读人员
    private void exportDealerNoRead(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        List<Map> resultList = notificationFeedbackMapper.selectListBySql4Excel(queryParam);

        Map<String, List<Map>> excelData = new HashMap<>();
        excelData.put("经销商端未读人员信息", resultList);
        List<ExcelExportColumn> exportColumnList = new ArrayList<>();

        exportColumnList.add(new ExcelExportColumn("ownerCode", "经销商代码"));
        exportColumnList.add(new ExcelExportColumn("dealerName", "经销商名称"));
        exportColumnList.add(new ExcelExportColumn("feedbackUserName", "员工姓名"));

        excelService.generateExcel(excelData, exportColumnList, "经销商端未读人员列表.xls", request, response);
    }

}
